package com.example.community.controller;

import com.example.community.entity.DiscussPost;
import com.example.community.entity.Page;
import com.example.community.service.ElasticsearchService;
import com.example.community.service.LikeService;
import com.example.community.service.UserService;
import com.example.community.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: huang
 * @Date: 2021/10/7 11:02
 * @Description:
 */
@Controller
public class SearchController implements CommunityConstant {

    @Autowired
    private ElasticsearchService elasticsearchService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    /**
     * 搜索功能请求
     * @param keyword   搜索关键字
     * @param page
     * @param model
     * @return          因为我们是get请求，所以我们把keyword放在url后面
     *                  如：search?keyword=xxx
     *                  1、get请求，keyword参数通过路径传递
     * 2、先从Es服务器中搜索帖子
     * elasticsearchService.searchDiscussPost方法。page.getCurrent() 获取当前页，但是是从1开始，因此先减1；page.getLimit() 每页显示多少条数据
     * 3、聚合数据
     * 根据搜索结果，封装一个 List<Map<String, Object>>。每个post实体生成一个Map，并储存帖子、作者、点赞数量
     * 4、最后把 Map和keyword传进model里。
     */
    @RequestMapping(path = "/search", method = RequestMethod.GET)
    public String search(String keyword, Page page, Model model) {
        //搜索帖子
        org.springframework.data.domain.Page<DiscussPost> searchResult =
                elasticsearchService.searchDiscussPost(keyword, page.getCurrent() - 1, page.getLimit());

        //把搜索到的数据聚合起来
        List<Map<String, Object>> discussPosts = new ArrayList<>();
        if (searchResult != null) {
            //遍历 searchResult 放入 Map 中
            for (DiscussPost post : searchResult) {
                Map<String, Object> map = new HashMap<>();
                //帖子存入
                map.put("post", post);
                //帖子发布作者存入
                map.put("user", userService.findUserById(post.getUserId()));
                //帖子的点赞数量存入
                map.put("likeCount", likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId()));

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts", discussPosts);
        model.addAttribute("keyword", keyword);

        //设置分页信息
        page.setPath("/search?keyword=" + keyword);
        page.setRows(searchResult == null ? 0 : (int) searchResult.getTotalElements());

        return "/site/search";
    }

}
